package com.ninetaildemonfox.zdl.socialproject.mvp.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.github.promeg.pinyinhelper.Pinyin;
import com.github.promeg.tinypinyin.lexicons.android.cncity.CnCityDict;
import com.google.gson.Gson;
import com.hyphenate.easeui.utils.map.BaseUrl;
import com.kongzue.baseokhttp.HttpRequest;
import com.kongzue.baseokhttp.listener.ResponseListener;
import com.kongzue.baseokhttp.util.Parameter;
import com.kongzue.dialog.v3.WaitDialog;
import com.ninetaildemonfox.zdl.socialproject.base.BaseActivity;
import com.ninetaildemonfox.zdl.socialproject.R;
import com.ninetaildemonfox.zdl.socialproject.SpApplication;
import com.ninetaildemonfox.zdl.socialproject.data.entity.CityListBean;
import com.ninetaildemonfox.zdl.socialproject.mvp.ui.adapter.CityAdapter;
import com.ninetaildemonfox.zdl.socialproject.mvp.ui.fragment.SearchFragment;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import me.yokeyword.indexablerv.EntityWrapper;
import me.yokeyword.indexablerv.IndexableAdapter;
import me.yokeyword.indexablerv.IndexableLayout;
import me.yokeyword.indexablerv.SimpleHeaderAdapter;

/**
 * @author NineTailDemonFox
 * @date 2019/7/18 13:51
 * 功能描述： 城市选择器
 * 联系方式：1037438704@qq.com
 */


public class CityListSelectActivity extends BaseActivity {

    private SearchFragment mSearchFragment;
    //    private SearchView mSearchView;
    private SimpleHeaderAdapter mHotCityAdapter;

    private ImageView iamge_left_finish;
    private TextView text_center_title;
    private IndexableLayout indexableLayout;
    private List<CityListBean.DataBean> gpsCity;
    private SimpleHeaderAdapter gpsHeaderAdapter;
    private List<CityListBean.DataBean> citylist;
    private CityAdapter adapter;
    private String location_me;
    private List<CityListBean.DataBean> relist = new ArrayList<>();

    @BindView(R.id.image_left_finish)
    ImageView imageLeftFinish;
    @BindView(R.id.text_mycity)
    TextView text_mycity;
    @BindView(R.id.edit_search)
    EditText editSearch;
    @BindView(R.id.text_dangqianweizhi)
    TextView text_dangqianweizhi;


    @Override
    protected int getLayoutResource() {
        return R.layout.activity_city_list_select;
    }

    @Override
    protected void onInitialization(Bundle bundle) {
        initView();
        initDatas();
    }

    private void initDatas() {
        text_center_title.setText("城市选择");
        imageLeftFinish.setVisibility(View.VISIBLE);
        imageLeftFinish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        indexableLayout.setLayoutManager(new LinearLayoutManager(this));
        // 多音字处理
        Pinyin.init(Pinyin.newConfig().with(CnCityDict.getInstance(this)));

        // 快速排序。  排序规则设置为：只按首字母  （默认全拼音排序）  效率很高，是默认的10倍左右。  按需开启～
        indexableLayout.setCompareMode(IndexableLayout.MODE_FAST);
        // setAdapter
        adapter = new CityAdapter(me);

        indexableLayout.setAdapter(adapter);
        // set Center OverlayView
        indexableLayout.setOverlayStyle_Center();
        citylist();


        adapter.setOnItemContentClickListener(new IndexableAdapter.OnItemContentClickListener<CityListBean.DataBean>() {

            @Override
            public void onItemClick(View v, int originalPosition, int currentPosition, CityListBean.DataBean entity) {
                Bundle bundle = new Bundle();
                Intent i = new Intent();
                bundle.putString("city", entity.getRegion_name());
                bundle.putString("id", entity.getId());
                bundle.putString("getLat", entity.getLat());
                bundle.putString("getLng", entity.getLng());
                i.putExtras(bundle);
                setResult(RESULT_OK, i);
                finish();
            }
        });

        adapter.setOnItemTitleClickListener(new IndexableAdapter.OnItemTitleClickListener() {
            @Override
            public void onItemClick(View v, int currentPosition, String indexTitle) {
                //这是是点击A B 标签的按钮
            }
        });
        initSearch();
    }

    private void initView() {
        if (SpApplication.CITY == null) {
            text_mycity.setText("请打开定位");
        } else {
            text_mycity.setText(SpApplication.CITY);
        }
        text_dangqianweizhi.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Bundle bundle = new Bundle();
                Intent i = new Intent();
                bundle.putString("city", text_dangqianweizhi.getText().toString().trim());
                bundle.putString("getLat", "");
                bundle.putString("getLng", "");
                i.putExtras(bundle);
                setResult(RESULT_OK, i);
                finish();
            }
        });
        text_mycity.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (text_mycity.getText().toString().equals("请打开定位")) {
                    return;
                }
                Bundle bundle = new Bundle();
                Intent i = new Intent();
                bundle.putString("city", SpApplication.CITY);
                bundle.putString("getLat", "");
                bundle.putString("getLng", "");
                i.putExtras(bundle);
                setResult(RESULT_OK, i);
                finish();
            }
        });

        citylist = new ArrayList<>();
        iamge_left_finish = (ImageView) findViewById(R.id.image_left_finish);
        text_center_title = (TextView) findViewById(R.id.text_center);
        mSearchFragment = (SearchFragment) getSupportFragmentManager().findFragmentById(R.id.search_fragment);
        indexableLayout = (IndexableLayout) findViewById(R.id.indexableLayout);
//        mSearchView = (SearchView) findViewById(R.id.searchview);
        iamge_left_finish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    private void initSearch() {
        getSupportFragmentManager().beginTransaction().hide(mSearchFragment).commit();
        editSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {


                if (s.toString().length() == 0) {
                    if (!mSearchFragment.isHidden()) {
                        getSupportFragmentManager().beginTransaction().hide(mSearchFragment).commit();
                    }
                } else {
                    if (mSearchFragment.isHidden()) {
                        getSupportFragmentManager().beginTransaction().show(mSearchFragment).commit();
                    }
                }
                if (s.toString() != null) {
                    mSearchFragment.bindQueryText(s.toString());
                }
            }
        });

//        mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
//            @Override
//            public boolean onQueryTextSubmit(String query) {
//                return false;
//            }
//
//            @Override
//            public boolean onQueryTextChange(String newText) {
//                if (newText.trim().length() > 0) {
//                    if (mSearchFragment.isHidden()) {
//                        getSupportFragmentManager().beginTransaction().show(mSearchFragment).commit();
//                    }
//                } else {
//                    if (!mSearchFragment.isHidden()) {
//                        getSupportFragmentManager().beginTransaction().hide(mSearchFragment).commit();
//                    }
//                }
//                mSearchFragment.bindQueryText(newText);
//                return false;
//            }
//        });
    }

    @Override
    public void onBackPressed() {
        if (!mSearchFragment.isHidden()) {
            // 隐藏 搜索
            editSearch.setText("");
//            mSearchView.setQuery(null, false);
            getSupportFragmentManager().beginTransaction().hide(mSearchFragment).commit();
            return;
        }
        super.onBackPressed();
    }

    /**
     * 获取城市列表
     */
    private void citylist() {
        WaitDialog.show(me, "数据加载中");
        HttpRequest.POST(me, BaseUrl.BaseHttpUrl + "Region/regionListAndroid"
                , new Parameter()
                , new ResponseListener() {
                    @Override
                    public void onResponse(String response, Exception error) {
                        if (error == null) {
                            WaitDialog.dismiss();
                            if (response == null) {
                                return;
                            }
                            Gson gson = new Gson();
                            CityListBean cityListBean = gson.fromJson(response, CityListBean.class);
                            citylist = cityListBean.getData();
                            for (int i = 0; i < citylist.size(); i++) {
                                Log.d("zdl", "========" + citylist.get(i).getRegion_name());
                            }
                            adapter.setDatas(citylist, new IndexableAdapter.IndexCallback<CityListBean.DataBean>() {
                                @Override
                                public void onFinished(List<EntityWrapper<CityListBean.DataBean>> datas) {
                                    // 数据处理完成后回调
                                    mSearchFragment.bindDatas(citylist);
                                    // mProgressBar.setVisibility(View.GONE);
                                }
                            });
                        }
                    }
                });
    }
}